package com.blobfish.fiction.book;

import cn.hutool.core.util.ReUtil;
import com.blobfish.fiction.common.model.BookChapter;
import com.jfinal.log.Log;
import com.jfinal.plugin.activerecord.Db;
import com.jfinal.plugin.activerecord.Record;
import org.apache.commons.collections.CollectionUtils;

import java.util.List;

/**
 * 小说章节service
 *
 * @author blobfish
 */
public class BookChapterService {
    private BookChapter dao = new BookChapter();
    private static final Log log = Log.getLog(BookChapterService.class);

    /**
     * 判断书本编号是否存在
     *
     * @param chapterNum 章节编号
     * @return 返回结果
     */
    public Boolean isExists(String chapterNum) {
        List<BookChapter> bookList = dao.find("select * from book_chapter where chapter_num = ?", chapterNum);
        if (bookList.size() > 0) {
            return Boolean.TRUE;
        } else {
            return Boolean.FALSE;
        }
    }

    /**
     * 新增方法
     *
     * @param bookChapter 待新增的数据
     */
    public synchronized void add(BookChapter bookChapter) {
        if (bookChapter == null) {
            log.error("要保存的数据不存在!");
            return;
        }
        if (!isExists(bookChapter.getChapterNum())) {
            bookChapter.save();
        }
    }

    /**
     * 添加url方法
     *
     * @param url     待添加的路径
     * @param urlList 保存路径的集合
     */
    public void addUrl(String url, List<String> urlList) {
        try {
            String url1 = url + "_1.html";
            if (!isDownload(url1)) {
                urlList.add(url1);
            }
            String url2 = url + "_2.html";
            if (!isDownload(url2)) {
                urlList.add(url2);
            }
        } catch (Exception e) {
            log.error("解析下载路径时发生错误:" + e.getMessage());
        }
    }

    /**
     * 判断该url是否已经下载
     * @param url 路径
     * @return 返回结果
     */
    public boolean isDownload(String url) {
        if (ReUtil.isMatch("https://m\\.wujixiaoshuo\\.com/\\w+/\\d+_\\d+\\.html", url) && url.indexOf("all") == -1) {
            // 判断该章节是否已经下载
            String[] urlSplits = url.split("/");
            String bookNo = urlSplits[urlSplits.length - 2];
            String chapterNum = urlSplits[urlSplits.length - 1];
            chapterNum = chapterNum.substring(0, chapterNum.indexOf(".html"));
            List<BookChapter> resultList = dao.find("select * from book_chapter where book_no = ? and chapter_num = ?", bookNo, chapterNum);
            return (CollectionUtils.isNotEmpty(resultList) && resultList.size() > 0);
        }
        return true;
    }

    /**
     * 根据小说编号获取本地最新章节
     * @param bookNo 小说编号
     * @return 返回本地最新章节
     */
    public Long getLastestChapterNumByBookNo(String bookNo) {
        Record record = Db.findFirst("select max(chapter_num_main) as lastest_chapter_num from book_chapter where book_no = ?", bookNo);
        return record == null ? 0L : record.getLong("lastest_chapter_num");
    }
}
